import WebIM from "@/utils/WebIM";
import axios from "axios";
import {getToken} from "@/utils/auth";
import {AddMessage} from "@/api/message";

const chat = {
	state: {
		friends: [],
		messageList: [],
		currentMsg: [],
		unreadMsg: {},
		pushedStream: false,
		timer: undefined,
		confrId: undefined
	},
	mutations: {
		setFriends: (state, friends) => {
			state.friends = friends;
		},
		setMessageList: (state, messageList) => {
			state.messageList = messageList;
		},
		setCurrentMsg: (state, currentMsg) => {
			state.currentMsg = currentMsg;
		},
		setUnreadMsg: (state, unreadMsg) => {
			state.unreadMsg = unreadMsg;
		},
		setPushedStream: (state, pushedStream) => {
			state.pushedStream = pushedStream;
		},
		setTimer: (state, timer) => {
			state.timer = timer;
		},
		setConfrId: (state, confrId) => {
			state.confrId = confrId;
		},
		pushMessageList: (state, message) => {
			state.messageList.push(message)
		},
		setPreStatus: (state, preId) => {
			for (let i = 0; i < state.messageList.length; i++) {
				if(state.messageList[i].prescribe) {
					if(state.messageList[i].prescribe.prescribeId == preId) {
						state.messageList[i].prescribe.status = 1;
					}
				}
			}
		}
	},
	actions: {
		getFriends: ({commit, state}) => {
			try {
				return new Promise((resolve, reject) => {
					WebIM.conn.getRoster({
						success: (roster) => {
							commit('setFriends', roster);
							resolve()
						}
					})
				})
			} catch (e) {
				console.error("获取好友失败!", e);
			}
		},
		getMessages: ({commit, state}, userId) => {
			return new Promise((resolve, reject) => {
				const option = {
					queue: userId,
					count: 20,
					success: (res) => {
						if(res.length && !state.messages[userId]) {
							state.messages[userId]= res;
							commit('setMessages', state.messages);
						}
						resolve()
					},
					fail: (e) => {
						console.error(e)
						reject()
					}
				}
				WebIM.conn.fetchHistoryMessages(option);
			})
		},
		getCurrentMsg({commit, state}, userId) {
			commit('setCurrentMsg', state.messages[userId]);
		},
		sendTextMsg({commit, state}, params) {
			return new Promise((resolve, reject) => {
				let message = new WebIM.message('txt', WebIM.conn.getUniqueId());
				let ext = {orderId: params.orderId};
				if(params.type == 'PRE') {
					ext.isPrescribe = true;
				}
				console.log(params)
				message.set({
					msg: params.message,
					to: params.receiver,
					chatType: 'singleChat',
					ext: ext,
					success: (id, serverMsgId) => {
            			console.info(serverMsgId);
						resolve();
					},
					fail: (e) => {
						console.error(e);
						reject();
					}
				});
				WebIM.conn.send(message.body);
			})
		},
		sendImgMsg({commit, state}, params) {
			return new Promise((resolve, reject) => {
				let id = WebIM.conn.getUniqueId();
				let msg = new WebIM.message("img", id);
				let imgId = null;
				let imgUri = null;
				msg.set({
					apiUrl: WebIM.config.apiURL,
					file: params.file,
					ext: {
						orderId: params.orderId
					},
					to: params.receiver,
					chatType: 'singleChat',
					onFileUploadError: function(error){
						// 消息上传失败
						console.log("图片上传失败", error);
						params.callback();
					},
					onFileUploadComplete: function(data){
						console.log(data);
						imgId = data.entities[0].uuid;
						imgUri = data.uri;
						// 消息上传成功
						params.callback();
					},
					success: function () {
						axios.post(process.env.VUE_APP_BASE_API + "/common/upload", params.formData, {
							headers: {
								'Content-Type': 'multipart/form-data',
								Authorization: 'Bearer ' + getToken()
							}
						}).then(res => {
							if(res.data.code === 200) {
								// 存库里
								let arg = {
									orderId: params.orderId,
									receiver: params.receiver,
									sender: params.sender,
									message: res.data.fileName,
									type: 'IMG'
								}
								AddMessage(arg).then(res => {
									commit('pushMessageList', arg);
									resolve();
								})
							}
						})
						console.log('Success');
					},
					fail: function(e){
						//如禁言、拉黑后发送消息会失败
						reject()
						console.log("Fail");
					},
					flashUpload: WebIM.flashUpload
				});
				WebIM.conn.send(msg.body);
			})
		}
	},
	getters: {
		friends: state => state.friends,
		messageList: state => state.messageList,
		currentMsg: (state) => state.currentMsg,
		unreadMsg: (state) => state.unreadMsg,
		pushedStream: (state) => state.pushedStream,
		timer: (state) => state.timer,
		confrId: (state) => state.confrId
	}
}

export default chat
